<template>
  <div>
    <el-card shadow="hover" style="margin: 18px 18px 0 18px">
      <template slot="header">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="showAddTrademarkDialogHandler()"
          >添加</el-button
        >
      </template>
      <el-table :data="trademarks">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              @click="showAddTrademarkDialogHandler(row)"
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteTrademarkHandler(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        :total="total"
        :page-size="limit"
        :page-sizes="[5, 10, 15]"
        :current-page="page"
        layout="prev, pager, next, jumper,->,sizes,total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="messageType + '品牌'"
      :visible.sync="isShowAddTrademarkDialog"
      top="0"
    >
      <el-form
        label-width="100px"
        :model="formData"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="onSuccessHandler"
            :before-upload="beforeUploadHandler"
          >
            <img
              class="avatar"
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowAddTrademarkDialog = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademarkHandler"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  requestTrademarkList,
  requestTrademarkListByPage,
  requestSaveBaseTrademark,
  requestUpdateBaseTrademark,
  requestDeleteBaseTrademark,
} from "@/api/trademark";
import { Message, MessageBox } from "element-ui";

export default {
  name: "Trademark",
  data() {
    return {
      trademarks: [],
      // 当前页数
      page: 1,
      // 每页显示条数
      limit: 5,
      // 总条数
      total: 0,
      messageType: "",
      isShowAddTrademarkDialog: false,
      formData: {
        tmName: "",
        logoUrl: "",
      },
      uploadUrl: "http://gmall-h5-api.atguigu.cn/admin/product/upload",
      formRef: "",
      rules: {
        tmName: [
          {
            required: true,
            min: 1,
            max: 20,
            message: "品牌名称必须是1-20个字符之间",
            trigger: "blur",
          },
        ],
        logoUrl: [
          {
            required: true,
            validator(rule, value, callback) {
              if (value == "") {
                // 调用callback表示当前验证结束，callback中传入值表示有错误，不传入任何值，表示验证成功
                callback("品牌名称必填");
              } else {
                const ext = value.substring(value.lastIndexOf(".") + 1);
                // console.log(ext);
                if (!["png", "jpg", "gif"].includes(ext)) {
                  callback("品牌LOGO必须是图片");
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    // 初始化品牌管理数据
    async getTrademarkList() {
      console.log(this);
      const { page, limit } = this;
      const result = await requestTrademarkListByPage(page, limit);
      // console.log(result);
      this.trademarks = result.data.records;
      this.total = result.data.total;
    },
    // 当前页数改变时，更新数据
    handleCurrentChange(v) {
      this.page = v;
      this.getTrademarkList();
    },
    // 每页显示条数改变时
    handleSizeChange(v) {
      this.limit = v;
      this.getTrademarkList();
    },
    // 点击添加和编辑品牌按钮
    showAddTrademarkDialogHandler(data) {
      // console.log(this);
      console.log(data);

      this.isShowAddTrademarkDialog = true;
      if (data) {
        this.formData = { ...data };
        this.messageType = "编辑";
      } else {
        this.formData = {
          tmName: "",
          logoUrl: "",
        };
        this.messageType = "添加";
      }
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
    },
    // 图片上传之前
    beforeUploadHandler(rawFile) {
      if (!["image/png", "image/jpg", "image/gif"].includes(rawFile.type)) {
        return false;
      }
      if (rawFile.size > 102400) {
        return false;
      }
    },
    // 图片上传成功后
    onSuccessHandler(response, uploadFile, uploadFiles) {
      // 把上传成功后的文件地址赋值给 formData.value.logoUrl
      if (response.code === 200) {
        this.formData.logoUrl = response.data;
      }
    },
    // 添加确定提交品牌数据
    async addOrUpdateTrademarkHandler() {
      try {
        try {
          await this.$refs["formRef"].validate();
          this.isShowAddTrademarkDialog = false;
          // 通过判断 formData 中是否存在 id 来调用不同的api
          if (this.messageType == "编辑") {
            await requestUpdateBaseTrademark(this.formData);
          } else {
            await requestSaveBaseTrademark(this.formData);
            this.page = Math.ceil((this.total + 1) / this.limit);
          }
          this.getTrademarkList();
          Message.success(this.messageType + "成功");
        } catch (e) {
          console.log("校验失败");
        }
      } catch (e) {
        Message.success(this.messageType + "失败");
      }
    },
    // 删除品牌
    async deleteTrademarkHandler(id) {
      try {
        await MessageBox({
          title: "提示",
          message: "你确定要删除吗？",
          type: "error",
        });
        await requestDeleteBaseTrademark(id);
        this.getTrademarkList();
        Message.success("删除成功");
      } catch (e) {
        Message.success("删除失败");
      }
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

function nextTick(arg0: () => void) { throw new Error('Function not
implemented.'); } function nextTick(arg0: () => void) { throw new
Error('Function not implemented.'); }
